package javaNIO1.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

/**
 * Created with Intel IDEA.
 * 用来管理异步连接的可用代码
 *  SocketChannel 是面向流的，有连接的 即可以用下tcp/ip 协议
 * @Auther: gjt
 * @Date: 2024/7/21 9:51
 */
public class ConnectAsync {

    private static int PORT = 13;

    private static String HOST = "152.136.138..218";

    //
    public static void main(String[] args) {
        if (args.length > 0) {
            PORT = Integer.parseInt(args[0]);
        }

        InetSocketAddress address = new InetSocketAddress(HOST, PORT);
        // 先初始化通道  之后再连接
        try (SocketChannel socketChannel = SocketChannel.open()) {
            socketChannel.configureBlocking(false);

            System.out.println("Initiating connection");
            socketChannel.connect(address);

            // note finishConnect() 和 connect() 方法是同步的 成功都成功，失败都失败
            while (!socketChannel.finishConnect()) {
                System.out.println("连接失败，之后做操作");
            }

            System.out.println("connection established");

            // 下一步就是使用通道
            // 用之前检测是否已经连接上
            if(!socketChannel.isConnected()){
                System.out.println("么有连接成功 ");
            }else {
                System.out.println("连接成功，继续操作");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
